from db.metastore import connect_with_pocketbase, user_auth_via_client, client_create_new, client_delete_record, \
    client_fetch_from, client_fetch_full_list_from, client_update_to
from application.handle_exception import pb_operation_exception
from domain.authentication import User
from domain.juice import FileSystemInDB, FileSystem


async def add_new_file_system_record(
        new_record: FileSystemInDB,
        user: User
):
    with connect_with_pocketbase() as db_client:
        _ = user_auth_via_client(
            client=db_client,
            user=user
        )
        create_response = await client_create_new(
            client=db_client,
            collection="juices",
            data=new_record.dict()
        )
        if not create_response:
            raise pb_operation_exception
    return create_response


async def view_juicefs_configuration(
        target_fs_id: str,
        user: User
):
    with connect_with_pocketbase() as db_client:
        _ = user_auth_via_client(
            client=db_client,
            user=user
        )
        if target_fs_id is None:
            record_response = await client_fetch_full_list_from(
                client=db_client,
                collection="juices"
            )
        else:
            record_response = await client_fetch_from(
                client=db_client,
                collection="juices",
                target_id=target_fs_id
            )

    return record_response


async def update_juicefs_configuration(
        user: User,
        update_record_id: str,
        new_fs_conf: FileSystem,
):
    with connect_with_pocketbase() as db_client:
        _ = user_auth_via_client(
            client=db_client,
            user=user
        )
        record_response = await client_fetch_from(
            client=db_client,
            collection="juices",
            target_id=update_record_id
        )
        record_dict = record_response.__dict__
        new_fs_record = FileSystemInDB(
            id=record_dict['id'],
            uuid=user.uuid.hex,
            name=record_dict['name'],
            fs_definition=new_fs_conf.json()
        )
        update_record_response = await client_update_to(
            client=db_client,
            collection="juices",
            target_id=update_record_id,
            data=new_fs_record.dict()
        )
        if not update_record_response:
            raise pb_operation_exception
    return update_record_response


async def delete_file_system_record(
        target_fs_id: str,
        user: User
):
    with connect_with_pocketbase() as db_client:
        _ = user_auth_via_client(
            client=db_client,
            user=user
        )
        null_content_response = await client_delete_record(
            client=db_client,
            collection="juices",
            target_id=target_fs_id
        )
        if not null_content_response:
            raise pb_operation_exception
    return null_content_response
